<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.orderNo" placeholder="请输入订单编号" style="width: 200px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.userName" placeholder="请输入用户名称" style="width: 200px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.orderStatus" placeholder="订单状态" class="filter-item" style="width: 150px;">
        <el-option label="全部" value=""></el-option>
        <el-option label="待处理" value="1"></el-option>
        <el-option label="已接单" value="2"></el-option>
        <el-option label="服务中" value="3"></el-option>
        <el-option label="已完成" value="4"></el-option>
        <el-option label="已取消" value="5"></el-option>
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
        @click="handleCreate">
        新增
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
        @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;"
      @sort-change="sortChange">
      <el-table-column label="订单ID" prop="orderId" sortable="custom" align="center" width="60"
        :class-name="getSortClass('orderId')">
        <template slot-scope="{row}">
          <span>{{ row.orderId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单编号" width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderNo }}</span>
        </template>
      </el-table-column>

      <el-table-column label="用户ID" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.userId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="护工ID" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nurseId || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="服务标题" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="服务类型" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.serviceType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="100px" align="center" prop="orderStatus" :formatter="statusFormatter">
      </el-table-column>
      <el-table-column label="服务时间" min-width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.startDate }} 至 {{ row.endDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="护理地点" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.careLocation }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.price || '待协商' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <!-- 抽屉模态框 -->
    <el-drawer :title="dr_title" :before-close="handleClose" :visible.sync="dialog" direction="rtl"
      custom-class="demo-drawer" ref="drawer" size="35%">
      <div class="drawer-scroll-container">
        <div class="demo-drawer__content">
          <el-form :model="form" :rules="rules" ref="form">
            <el-form-item v-if='show_id_item' label="订单ID" :label-width="formLabelWidth">
              <el-input v-model="form.orderId" readonly></el-input>
            </el-form-item>
            <el-form-item label="订单编号" :label-width="formLabelWidth" prop="orderNo">
              <el-input v-model="form.orderNo" autocomplete="off" :readonly="show_id_item"></el-input>
            </el-form-item>
            <el-form-item label="用户ID" :label-width="formLabelWidth" prop="userId">
              <el-input v-model="form.userId" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="护工ID" :label-width="formLabelWidth">
              <el-input v-model="form.nurseId" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="服务标题" :label-width="formLabelWidth" prop="title">
              <el-input v-model="form.title" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="服务类型" :label-width="formLabelWidth" prop="serviceType">
              <el-select v-model="form.serviceType" placeholder="请选择服务类型">
                <el-option label="住院陪护" value="住院陪护"></el-option>
                <el-option label="老人日常陪护" value="老人日常陪护"></el-option>
                <el-option label="母婴护理" value="母婴护理"></el-option>
                <el-option label="康复护理" value="康复护理"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="订单状态" :label-width="formLabelWidth">
              <el-select v-model="form.orderStatus" placeholder="请选择订单状态">
                <el-option label="待处理" value="1"></el-option>
                <el-option label="已接单" value="2"></el-option>
                <el-option label="服务中" value="3"></el-option>
                <el-option label="已完成" value="4"></el-option>
                <el-option label="已取消" value="5"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开始日期" :label-width="formLabelWidth" prop="startDate">
              <el-date-picker v-model="form.startDate" type="date" placeholder="选择开始日期" format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
            <el-form-item label="结束日期" :label-width="formLabelWidth" prop="endDate">
              <el-date-picker v-model="form.endDate" type="date" placeholder="选择结束日期" format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
            <el-form-item label="护理地点" :label-width="formLabelWidth" prop="careLocation">
              <el-input v-model="form.careLocation" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="详细地址" :label-width="formLabelWidth" prop="address">
              <el-input v-model="form.address" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="护理时间" :label-width="formLabelWidth" prop="careTime">
              <el-input v-model="form.careTime" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="联系电话" :label-width="formLabelWidth" prop="phone">
              <el-input v-model="form.phone" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="服务描述" :label-width="formLabelWidth" prop="description">
              <el-input v-model="form.description" type="textarea" rows="3"></el-input>
            </el-form-item>
            <el-form-item label="服务价格" :label-width="formLabelWidth">
              <el-input v-model="form.price" autocomplete="off" type="number"></el-input>
            </el-form-item>
          </el-form>
          <div class="demo-drawer__footer">
            <el-button @click="cancelForm">取 消</el-button>
            <el-button type="warning" @click="resetForm">重置</el-button>
            <el-button type="primary" @click="save_btn">提交</el-button>
          </div>
        </div>
      </div>
    </el-drawer>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    fetchList,
    del,
    updateStatus,
    add,
    update,
    fetchPv
  } from '@/api/backendApi';

  import waves from '@/directive/waves'
  import {
    parseTime
  } from '@/utils'
  import Pagination from '@/components/Pagination'

  export default {
    name: 'OrderTable',
    components: {
      Pagination
    },
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'info',
          2: 'primary',
          3: 'success',
          4: 'warning',
          5: 'danger'
        }
        return statusMap[status]
      }
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          pageNo: 1,
          pageSize: 5,
          orderNo: '',
          userName: '',
          orderStatus: '',
          sort: '+orderId'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          orderNo: [{
            required: true,
            message: '订单编号不能为空！',
            trigger: 'blur'
          }],
          userId: [{
            required: true,
            message: '用户ID不能为空！',
            trigger: 'blur'
          }],
          title: [{
            required: true,
            message: '服务标题不能为空！',
            trigger: 'blur'
          }],
          serviceType: [{
            required: true,
            message: '请选择服务类型！',
            trigger: 'change'
          }],
          startDate: [{
            required: true,
            message: '请选择开始日期！',
            trigger: 'change'
          }],
          endDate: [{
            required: true,
            message: '请选择结束日期！',
            trigger: 'change'
          }],
          careLocation: [{
            required: true,
            message: '护理地点不能为空！',
            trigger: 'blur'
          }],
          phone: [{
            required: true,
            message: '联系电话不能为空！',
            trigger: 'blur'
          }, {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }],
          description: [{
            required: true,
            message: '服务描述不能为空！',
            trigger: 'blur'
          }]
        },
        downloadLoading: false,
        dialog: false,
        loading: false,
        form: {
          orderId: '',
          orderNo: '',
          userId: '',
          nurseId: '',
          orderStatus: 1,
          title: '',
          category: 1,
          serviceType: '',
          requiredGender: 0,
          startDate: '',
          endDate: '',
          careLocation: '',
          address: '',
          careTime: '',
          phone: '',
          description: '',
          price: null,
          nurseName: null,
          userName: null
        },
        formLabelWidth: '100px',
        dr_title: '',
        show_id_item: false,
        loginUid: localStorage.getItem('uId')
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        fetchList(this.listQuery).then(res => {
          console.info('response==>', res)
          this.list = res.data.data.dataList;
          this.total = res.data.data.totalCount;

          setTimeout(() => {
            this.listLoading = false
          }, 500)
        }).catch(err => {
          console.error('获取订单列表失败:', err)
          this.listLoading = false
        })
      },
      /* 格式化订单状态 */
      statusFormatter(row, column, cellValue) {
        const statusMap = {
          1: '待处理',
          2: '已接单',
          3: '服务中',
          4: '已完成',
          5: '已取消'
        }
        return statusMap[cellValue] || '未知';
      },
      handleFilter() {
        this.listQuery.pageNo = 1
        this.getList()
      },
      sortChange(data) {
        const {
          prop,
          order
        } = data;
        if (prop === 'orderId') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+orderId'
        } else {
          this.listQuery.sort = '-orderId'
        }
        this.handleFilter()
      },
      handleCreate() {
        this.dr_title = '新增订单';
        this.dialog = true;
        this.show_id_item = false;
        this.clearFormData();
        // 生成订单编号
        const date = new Date();
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
        this.form.orderNo = `ORDER${year}${month}${day}${random}`;
      },
      // 清空表单数据
      clearFormData() {
        this.form = {
          orderId: '',
          orderNo: '',
          userId: '',
          nurseId: '',
          orderStatus: 1,
          title: '',
          category: 1,
          serviceType: '',
          requiredGender: 0,
          startDate: '',
          endDate: '',
          careLocation: '',
          address: '',
          careTime: '',
          phone: '',
          description: '',
          price: null,
          nurseName: null,
          userName: null
        }
      },
      // 重置
      resetForm() {
        this.clearFormData();
        // 新增状态下重新生成订单编号
        if (!this.show_id_item) {
          const date = new Date();
          const year = date.getFullYear();
          const month = (date.getMonth() + 1).toString().padStart(2, '0');
          const day = date.getDate().toString().padStart(2, '0');
          const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
          this.form.orderNo = `ORDER${year}${month}${day}${random}`;
        }
      },
      handleUpdate(row) {
        this.dr_title = '编辑订单';
        this.dialog = true;
        this.show_id_item = true;
        // 复制行数据到表单
        this.form = {
          ...row
        };
      },
      handleDelete(row, index) {
        this.$confirm(`此操作将永久删除编号为${row.orderNo}的订单, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          del(row.orderId).then(res => {
            if (res.code === 200) {
              this.$message({
                message: res.msg || '删除成功',
                type: 'success'
              });
              this.list.splice(index, 1);
              this.total--;
              this.getList();
            } else {
              this.$message.error(res.msg || '删除失败');
            }
          }).catch(err => {
            console.error(err);
            this.$message.error('操作异常，请联系管理员！');
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleFetchPv(pv) {
        fetchPv(pv).then(response => {
          this.pvData = response.data.pvData
          this.dialogPvVisible = true
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['订单编号', '用户ID', '服务标题', '服务类型', '订单状态', '服务时间', '联系电话']
          const filterVal = ['orderNo', 'userId', 'title', 'serviceType', 'orderStatus', 'startDate', 'phone']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '订单管理'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'orderStatus') {
            const statusMap = {
              1: '待处理',
              2: '已接单',
              3: '服务中',
              4: '已完成',
              5: '已取消'
            }
            return statusMap[v[j]] || '未知';
          } else if (j === 'startDate') {
            return `${v[j]} 至 ${v.endDate}`;
          } else {
            return v[j] !== null ? v[j] : '-';
          }
        }))
      },
      getSortClass(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      },
      handleClose(done) {
        if (this.loading) {
          return;
        }
        this.$confirm('确定要关闭吗？未保存的数据将丢失')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      cancelForm() {
        this.loading = false;
        this.dialog = false;
        clearTimeout(this.timer);
      },
      // 新增订单
      insert() {
        add(this.form).then(res => {
          if (res.code === 200) {
            this.$message({
              message: res.msg || '新增成功',
              type: 'success'
            });
            this.getList();
          } else {
            this.$message.error(res.msg || '新增失败');
          }
        }).catch(err => {
          console.error(err);
          this.$message.error('操作异常，请联系管理员！');
        })
      },
      // 修改订单
      edit() {
        update(this.form).then(res => {
          if (res.code === 200) {
            this.$message({
              message: res.msg || '修改成功',
              type: 'success',
            });
            this.getList();
          } else {
            this.$message.error(res.msg || '修改失败');
          }
        }).catch(err => {
          console.error('修改接口报错：', err);
          this.$message.error('操作异常，请联系管理员！');
        })
      },
      // 提交数据
      save_btn() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.form.orderId) {
              this.edit();
              this.getList();
            } else {
              this.insert();
              this.getList();
            }
            this.dialog = false;
          } else {
            console.log('验证失败！');
            return false;
          }
        });
      }
    }
  }
</script>




















<style scoped>
  .drawer-scroll-container {
    max-height: 90vh;
    overflow-y: auto;
    padding-right: 10px;
  }

  .drawer-scroll-container::-webkit-scrollbar {
    width: 6px;
  }

  .drawer-scroll-container::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 3px;
  }

  .demo-drawer__content {
    padding: 20px;
  }

  .demo-drawer__footer {
    margin-top: 20px;
    text-align: right;
  }

  .demo-drawer__footer .el-button {
    margin-left: 10px;
  }
</style>
